package com.bub.pay.framework.redis.redisson.config;

import com.bub.pay.framework.common.base.Cause;
import com.bub.pay.framework.common.base.Module;
import com.bub.pay.framework.common.exception.GlobalException;
import org.redisson.RedissonMultiLock;
import org.redisson.api.*;

import java.util.concurrent.TimeUnit;

/** 
 * @ClassName: RedissonDistributedLocker 
 * @Description:  Lock的接口
 * @author Leo.King
 * @version V1.0   
 */
public class RedissonLockerClient {

	private RedissonClient redissonClient;

   
    public RLock lock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        return lock;
    }

	/**
	 * 联锁
	 * 
	 * @param lockKeys
	 * @return
	 */
	public RedissonMultiLock lock( int leaseTim,String... lockKeys) {
		RLock[] locks = new RLock[lockKeys.length];
		for (int i = 0; i < lockKeys.length; i++) {
			RLock lock = redissonClient.getLock(lockKeys[i]);
			locks[i] = lock;
		}
		RedissonMultiLock lock = new RedissonMultiLock(locks);
		lock.lock(leaseTim, TimeUnit.SECONDS);
		return lock;
	}
    
    public RLock lock(String lockKey, int leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            lock.lock(leaseTime, TimeUnit.SECONDS);
        }catch (Exception e){
            throw new GlobalException(Module.merchant, Cause.mer_order_to_success_lock_error);
        }
        return lock;
    }
    
   
    public RLock lock(String lockKey, TimeUnit unit ,int timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, unit);
        return lock;
    }
    
   
    public boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException e) {
            return false;
        }
    }
    
   
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.unlock();
    }
    
   
    public void unlock(RLock lock) {
        lock.unlock();
    }
    
    public RMap<String, Object> getRmap(final String mapName) {
		return redissonClient.getMap(mapName);
	}

	public RMapCache<String, Object> getRMapCache(final String mapName) {
		return redissonClient.getMapCache(mapName);
	}

	public <T> RList<T> getRList(final String listName,Class<T> clz) {
		return redissonClient.getList(listName);
	}
	
    public void setRedissonClient(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

}
